<script lang="ts" setup>
import { groupBy } from 'xe-utils'
import { ClassroomApi } from '@/apis'

const props = withDefaults(defineProps<Props>(), {
  campusId: undefined,
  classroomId: undefined,
})

const emit = defineEmits(['update:campusId', 'update:classroomId'])

interface Props {
  campusId?: string
  classroomId?: string
  options?: any[]
}

const attrs = useAttrs()

const loading = ref(false)
const classroomList = ref<any[]>([])
const value = ref()

const getOptionList = async () => {
  loading.value = true
  await ClassroomApi.getList({}).then((res) => {
    classroomList.value = res
  }).finally(() => {
    loading.value = false
  })
}

const _options = computed(() => {
  const classroomGroup = groupBy(classroomList.value, 'campusName')
  return Object.keys(classroomGroup).map((campusName) => {
    return {
      value: classroomGroup[campusName][0].campusId,
      label: campusName,
      children: classroomGroup[campusName].map((item) => {
        return {
          value: item.id,
          label: item.name,
        }
      }),
    }
  })
})

const onChange = (value) => {
  if (!value) {
    emit('update:campusId', undefined)
    emit('update:classroomId', undefined)
    return
  }
  if (value && value.length === 1) {
    emit('update:campusId', value[0])
    emit('update:classroomId', undefined)
    return
  }
  if (value && value.length === 2) {
    emit('update:campusId', value[0])
    emit('update:classroomId', value[1])
  }
}

onMounted(() => {
  if (props.options) {
    classroomList.value = props.options
  } else {
    getOptionList()
  }
  if (!props.campusId && !props.classroomId) {
    value.value = undefined
  } else {
    value.value = [props.campusId, props.classroomId]
  }
})
</script>

<template>
  <a-cascader
    :default-value="value"
    :options="_options"
    v-bind="attrs"
    placeholder="校区/教室"
    allow-clear
    path-mode
    allow-search
    @change="onChange"
  />
</template>

<style lang='less' scoped>
</style>
